package com.shunhao.widgets.custom

import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.shunhao.rxlibrary.R


class HorizontalBarView : View {
    private var max = 100
    private var progress = 0

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)


    fun setMax(max: Int) {
        this.max = max
    }

    fun setProgress(progress: Int) {
        this.progress = progress
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val minimumWidth = suggestedMinimumWidth
        val specMode = MeasureSpec.getMode(widthMeasureSpec)
        val specSize = MeasureSpec.getSize(widthMeasureSpec)

        var width = 0
        when (specMode) {
            MeasureSpec.EXACTLY -> if (max > 0) { width = (specSize - resources.getDimension(R.dimen.margin_20).toInt()) / max * progress }
            MeasureSpec.AT_MOST -> width = specSize
            MeasureSpec.UNSPECIFIED -> width = minimumWidth.coerceAtLeast(specSize)
        }
        setMeasuredDimension(width, MeasureSpec.getSize(heightMeasureSpec))
    }
}
